package com.ruge._08_springboot_springdata_jpa.controller._03_mapping._02_oneToMany;

import com.ruge._08_springboot_springdata_jpa.Application;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import java.util.ArrayList;
import java.util.List;

/**
 * 创建人 ：爱丽丝、如歌
 * 创建时间 ：2019-07-05  22:43
 * 描述 ：一对多测试
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)//这里是启动类
public class TestOneToMany {
    @Autowired
    private EntityManager entityManager;

    @Test
    @Transactional
    public void testSave() {
        OneToManyClassModel classModel = new OneToManyClassModel("三年二班");
        OneToManyStuModel stuModel1 = new OneToManyStuModel("张三");
        OneToManyStuModel stuModel2 = new OneToManyStuModel("李四");
        OneToManyStuModel stuModel3 = new OneToManyStuModel("王五");
        List<OneToManyStuModel> list = new ArrayList<>();
        list.add(stuModel1);
        list.add(stuModel2);
        list.add(stuModel3);
        classModel.setOneToManyStuModel(list);
        entityManager.persist(stuModel1);
        entityManager.persist(stuModel2);
        entityManager.persist(stuModel3);
        entityManager.persist(classModel);
        entityManager.flush();
    }

    @Test
    @Transactional
    public void testUpdate() {
        OneToManyClassModel classModel =   entityManager.find(OneToManyClassModel.class,4);
        OneToManyStuModel stuModel1 =   entityManager.find(OneToManyStuModel.class,1);
        OneToManyStuModel stuModel2 =   entityManager.find(OneToManyStuModel.class,2);
        OneToManyStuModel stuModel3 =   entityManager.find(OneToManyStuModel.class,3);
        stuModel1.setName("张三1");
        stuModel2.setName("李四2");
        stuModel3.setName("王五3");
        classModel.setName("三年三班");
        List<OneToManyStuModel> list = new ArrayList<>();
        list.add(stuModel1);
        list.add(stuModel2);
        list.add(stuModel3);
        classModel.setOneToManyStuModel(list);
        entityManager.merge(stuModel1);
        entityManager.merge(stuModel2);
        entityManager.merge(stuModel3);
        entityManager.merge(classModel);
        entityManager.flush();
    }

    @Test
    @Transactional
    public void testDelete() {
        OneToManyStuModel stuModel1 =   entityManager.find(OneToManyStuModel.class,1);
        entityManager.remove(stuModel1);
        entityManager.flush();
    }

    @Test
    @Transactional
    public void testSelect() {
       List list = entityManager.createQuery("select  t from OneToManyClassModel t").getResultList();
       list.forEach(System.out::println);
    }
}
